﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections;
using System.Data.SqlClient;
using System.Data;
namespace InternetShop.Code
{
    public class Basket
    {
        #region Data

        Dictionary<Product, int> _goods = new Dictionary<Product, int>();

        #endregion

        #region Properties

        public string UserName { get; set; }

        public IEnumerable<Product> Goods { get { return _goods.Keys; } }

        #endregion

        #region Constructors

        public Basket()
        { 
            
        }

        public Basket(string username)
        {
            this.UserName = username;
        }

        #endregion

        #region Methods
        
        /**
         * <summary>Сохраняет корзину пользователя в базу</summary>
         * */
        public void Save()
        {
            if (!string.IsNullOrEmpty(UserName))
                foreach (var kvp in _goods)
                    _writeProductToBase(kvp.Key, kvp.Value);
        }
        /**
         * <summary>Добавляет товар в корзину</summary>
         * */
        public void AddProduct(Product prod, int quantity)
        {
            _goods.Add(prod, quantity);
        }
        /**
         * <summary>Удаляет товар из корзины</summary>
         * */
        public void RemoveProduct(Product prod)
        {
            _goods.Remove(prod);
            _deleteProductFromBase(prod);
        }

        public bool Contains(Product prod)
        {
            return _goods.Where(item => item.Key.ID == prod.ID).Count() == 1;
        }

        /**
         * <summary>Очищает корзину (удалает из базы)</summary>
         * */
        public void Clear() 
        {
            SqlParameter[] dbParams = {
                                          new SqlParameter("@UserName", UserName)
                                      };
            DataHelper.ExecNonQueryProc("BasketClear", dbParams);
            _goods.Clear();
        }

        /**
         * <summary>Загружает корзину пользователя из базы</summary>
         * */
        public static Basket LoadForUser(string username)
        {
            Basket result = new Basket(username);
            SqlParameter[] dbParams = {
                                          new SqlParameter("@UserName", username)
                                      };
            DataHelper.ExecFillingProc("BasketGetProductsAndQuantities", dbParams,
                                    delegate(IDataReader r) {
                                        while(r.Read()) {
                                            long q = (long)r["InBasket"];
                                            Product tmp = new Product();
                                            tmp.ID = (long?)r["ID"];
                                            tmp.Brand = r["Brand"].ToString();
                                            tmp.Model = r["Model"].ToString();
                                            tmp.Price = (decimal?)r["Price"];
                                            tmp.Description = r["Description"].ToString();
                                            tmp.Quantity = (long?)r["Quantity"];
                                            tmp.ImagePath = r["ImagePath"].ToString();
                                            result.AddProduct(tmp, (int)q);
                                        }
                                    });
            return result;
        }

        #endregion

        #region private Methods

        void _writeProductToBase(Product prod, int q)
        {
            if (string.IsNullOrEmpty(UserName))
                return;
            SqlParameter[] dbParams = {
                                          new SqlParameter("@UserName", UserName)
                                         ,new SqlParameter("@ProductID", prod.ID)
                                         ,new SqlParameter("@Quantity", q)
                                      }; 
            DataHelper.ExecNonQueryProc("BasketAddProduct", dbParams);
        }

        void _deleteProductFromBase(Product prod)
        {
            if (string.IsNullOrEmpty(UserName))
                return;
             SqlParameter[] dbParams = {
                                          new SqlParameter("@UserName", UserName)
                                         ,new SqlParameter("@ProductID", prod.ID)
                                      }; 
            DataHelper.ExecNonQueryProc("BasketDeleteProduct", dbParams);
        }
        
        #endregion
    }
}